import React, { useState } from 'react';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';

const SortableItem = ({ id, name, index, moveItem, children, depth }) => {
  const [, ref] = useDrag({
    type: 'ITEM',
    item: { id, index, depth },
  });

  const [, drop] = useDrop({
    // type: 'ITEM',
    accept: 'ITEM',
    hover: (draggedItem) => {
      if (draggedItem.id !== id || draggedItem.depth !== depth) {
        moveItem(draggedItem.index, index, draggedItem.depth);
        draggedItem.index = index;
        draggedItem.depth = depth;
      }
    },
  });

  return (
    <div
      ref={(node) => ref(drop(node))}
      style={{ marginLeft: depth * 20, padding: '8px', margin: '4px', background: 'lightblue' }}
    >
      {name}
      {children && children.length > 0 && (
        <div>
          {children.map((child, childIndex) => (
            <SortableItem
              key={child.id}
              id={child.id}
              name={child.name}
              index={childIndex}
              moveItem={moveItem}
              children={child.children}
              depth={depth + 1} // 递增深度属性
            />
          ))}
        </div>
      )}
    </div>
  );
};

const App = () => {
  const [items, setItems] = useState([
    {
      id: 1,
      name: 'Item 1',
      children: [
        { id: 2, name: 'Item 2', children: [] },
        {
          id: 3,
          name: 'Item 3',
          children: [
            { id: 4, name: 'Item 4', children: [] },
            { id: 5, name: 'Item 5', children: [] },
          ],
        },
      ],
    },
  ]);

  const moveItem = (fromIndex, toIndex, depth) => {
    const updatedItems = [...items];

    // 通过递归更新深度属性
    const updateDepth = (item, newDepth) => {
      item.depth = newDepth;
      item.children.forEach((child) => {
        updateDepth(child, newDepth + 1);
      });
    };

    const draggedItem = updatedItems[fromIndex];
    updateDepth(draggedItem, depth);

    updatedItems.splice(fromIndex, 1);
    updatedItems.splice(toIndex, 0, draggedItem);

    setItems(updatedItems);
  };

  return (
    <DndProvider backend={HTML5Backend}>
      <div>
        {items.map((item, index) => (
          <SortableItem
            key={item.id}
            id={item.id}
            name={item.name}
            index={index}
            moveItem={moveItem}
            children={item.children}
            depth={0}
          />
        ))}
      </div>
    </DndProvider>
  );
};

export default App;
